﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net;

namespace WpfDownload
{
	/// <summary>
	/// Handles downloading a list of Uri's to a distination
	/// </summary>
	public class DownloadHandler
	{
		private List<Task> tasks;
		private string destination;
		private string prefix;

		/// <summary>
		/// Initializes the list and sets the destination folder
		/// </summary>
		/// <param name="destination">a location with privilages to write the incoming files</param>
		public DownloadHandler(string destination, string prefix)
		{
			this.destination = destination;
			tasks = new List<Task>();
			this.prefix = prefix;
		}

		/// <summary>Will be fired when WebClient raises any change in any items in the list </summary>
		public event DownloadProgressChangedEventHandler ProgressChanged;
		/// <summary>Will be raised for any item in the list,
		/// By the time this event is raised, the handlers have been disassociated in this klass.  </summary>
		public event AsyncCompletedEventHandler Completed;

		public List<Task> Tasks { get { return tasks; } }
		public void Add(Uri uri)
		{
			tasks.Add(new Task(new DownloadRecord(uri)
			                   	{
			                   		DestinationFolder = destination,
			                   		Prefix = prefix
			                   	}));
		}

		/// <summary>
		/// Start a task for each Uri in the list.
		/// Also associates the event handlers
		/// </summary>
		public void Start()
		{
			foreach (var task in tasks)
			{
				task.Completed += DownloadFileCompleted;
				task.ProgressChanged += DownloadProgressChanged;
				task.Start();
			}
		}

		/// <summary>
		/// Stop the given task and remove the event handlers for the task item
		/// </summary>
		/// <param name="task">the task to stop</param>
		public void Stop(Task task)
		{
			task.Completed -= DownloadFileCompleted;
			task.ProgressChanged -= DownloadProgressChanged;
			task.Stop();
		}

		/// <summary>
		/// The event handler 
		/// </summary>
		/// <param name="sender">The Task</param>
		/// <param name="e">holds information about the task</param>
		void DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
		{
			if (ProgressChanged != null)
				ProgressChanged(sender, e);
		}

		/// <summary>
		/// The event handler 
		/// </summary>
		/// <param name="sender">The Task</param>
		/// <param name="e">holds information about the task</param>
		void DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
		{
			var task = sender as Task;
			task.Completed -= DownloadFileCompleted;
			task.ProgressChanged -= DownloadProgressChanged;

			if (Completed != null)
				Completed(sender, e);
		}

	}
}
